<template>
  <div class="myContainer">
    <el-row class="myTitleBorderBottom">
      <el-col :span="12" class="myLineHeight_40px">{{title}}</el-col>
      <el-col :span="12" class="myTextAlignRight">
        <a id="downlink"></a>
        <el-button type="primary" class="myBgGreen" @click="onExport" ref="exportBtn" :loading="loadingExport">导出Excel</el-button>
        <el-button type="primary" class="myBgGreen" @click="onPush">推送设置</el-button>
      </el-col>
    </el-row>
    <el-row class="myMarginTop_10px" :gutter="10">
      <el-col :span="6">
        <template>
          <el-cascader
            placeholder="全部项目/小区"
            :options="regionOptions"
            v-model="regionOptSelected"
          ></el-cascader>
        </template>
      </el-col>
      <el-col :span="8">
        <el-date-picker
          v-model="time"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-col>
      <el-col :span="3">
        <el-input placeholder="请输入关键词" v-model="kw"></el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" class="myBgGreen" @click="fuzzySearch">查 询</el-button>
      </el-col>
    </el-row>
    <el-row class="myMarginTop_10px">
      <el-col :span="24">
        <el-table
          ref="multipleTable"
          :data="list"
          :border = true
          :stripe = true
          v-loading="loading"
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            width="55">
          </el-table-column>
          <el-table-column type="expand">
            <template slot-scope="props">
              {{props.row.desc}}
            </template>
          </el-table-column>
          <el-table-column
            prop="area_name"
            label="所属小区"
            >
          </el-table-column>
          <el-table-column
            width="150"
            prop="order_id"
            label="订单号"
            >
          </el-table-column>
          <el-table-column
            width="150"
            label="支付金额(元)"
            >
            <template scope="scope">
              {{scope.row.fee | conversion}}
            </template>
          </el-table-column>
          <el-table-column
            width="150"
            prop="create_time"
            label="缴费时间"
            >
          </el-table-column>
          <el-table-column
            prop="room_name"
            label="缴费房产"
            >
          </el-table-column>
          <el-table-column
            width="150"
            prop="user_name"
            label="缴费用户"
            >
          </el-table-column>
          <el-table-column
            width="120"
            prop="phone"
            label="联系电话"
            >
          </el-table-column>
          <el-table-column
            width="100"
            label="操作">
            <template scope="scope">
                <el-button class="look" type="text" size="small" @click="onSync(scope.row.order_id,scope.$index)" :loading="isable[scope.$index]" v-if="scope.row.sync==false">同步</el-button> 
                <span v-else>已同步</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="block">                    
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page_num"
            :page-sizes="[10, 15]"
            :page-size="page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myTitleBorderBottom{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    border-bottom: 1px solid #dbdbdb;
    padding-bottom: 5px;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top:2px;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myMarginTop_10px{
    margin-top: 10px;
  }
  .myColorRed{
    color: #f00;
  }
</style>

<script>
  import { getPayList , syncData , keyMapping  } from '@/api/pay'
  import { extractAreaIds , onSetArea } from '@/utils/misc';
  import { getRegion } from '@/utils/localstorage';
  var XLSX = require('xlsx');
  export default {
    data(){
      return{  
        title:"自助缴费记录",    
        list:[],  
        loading:false,
        
        total:null, //总条数  
        page_num: 1, //当前页码
        page_size: 10, //每页显示多少条 

        kw:"",
        startTime:"",
        endTime:"",
        
        time:[],

        regionOptions: [],
        regionOptSelected: [],

        isable:[],
        syncText:"同步",
        loadingExport:false
      }
    },
    created() {
      document.title=this.title;
      this.regionOptions = getRegion();
      this.regionOptSelected.push(this.regionOptions[0].value,this.regionOptions[0].children[0].value,this.regionOptions[0].children[0].children[0].value);
      
      this.onGetPayList();
    },
    mounted () {
      this.outFile = document.getElementById('downlink');
    },
    computed: {
      areaIds() {
        return extractAreaIds(this.regionOptSelected, this.regionOptions);
      }
    },
    filters: {
      conversion(val){
        let data=val/100;
        return data.toFixed(2);
      }
    },
    methods:{
      fuzzySearch() {
         this.onGetPayList();
      },
      handleSizeChange(val) {
        this.page_size = val;
        this.onGetPayList();
      },
      handleCurrentChange(val) {
        this.page_num = val;
        this.onGetPayList();
      },
      onGetPayList(){//拉取自助缴费列表
        let vm=this;
        let params={
          page_num:vm.page_num,
          page_size:vm.page_size,
          area_id:vm.areaIds,
          start:vm.time?vm.time[0]:'',
          end:vm.time?vm.time[1]:'',
          kw:vm.kw
        }
        getPayList(params).then(response => {
          let res=response.data;
          vm.list=res.rows;
          vm.total=res.total;
          vm.isable = new Array(res.rows.length);
        }).catch(error => {
        })
      },
      onSync(order_id,index){
        let vm=this;
        vm.$set(vm.isable,index,true);
        syncData(order_id).then(response => {
          let res=response.data.result;
          if(res){
            vm.onGetPayList();
            vm.$message.success("执行成功！");
          }else{
            vm.$message.error("执行失败！");
            vm.$set(vm.isable,index,false);
          }
        }).catch(error => {
          vm.$message.error("执行失败！");
          vm.$set(vm.isable,index,false);
        })
      },
      onPush(){
        this.$router.push({
          path:'/payPush',
          query: {}
        })
      },
      onExport(){//导出
        let vm=this;
        let params={
          page_num:1,
          page_size:vm.total,
          area_id:vm.areaIds,
          start:vm.time[0]||'',
          end:vm.time[1]||'',
          kw:vm.kw
        }
        vm.loadingExport=true;
        getPayList(params).then(response => {
          let res=response.data.rows;
          if(res.length==0) {
            vm.loadingExport=false;
            vm.$message.info("没有可导出的数据！");
            return false;
          }
          let data = [{}]
          for (let k in res[0]) {
            data[0][k] = k
          }
          data = data.concat(res);
          let start=vm.time[0]||'';
          let end=vm.time[1]||'';
          vm.downloadExl(data, `自助缴费记录${start} ${end} ${vm.kw}`);
          vm.loadingExport=false;
          vm.$message.success(`导出成功！总共${res.length}条数据。`);
        }).catch(error => {
          console.log(error)
          vm.loadingExport=false;
          vm.$message.error("导出失败！");
        })
      },
      downloadExl: function (json, downName, type) {  // 导出到excel
        let keyMap = [] // 获取键
        for (let k in json[0]) {
          keyMap.push(k)
        }
        // console.info('keyMap', keyMap, json)
        let tmpdata = [] // 用来保存转换好的json
        json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
          v: v[k],
          position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
          tmpdata[v.position] = {
            v: keyMapping[v.v] || v.v
          }
        })
        let outputPos = Object.keys(tmpdata)  // 设置区域,比如表格从A1到D10
        let tmpWB = {
          SheetNames: ['自助缴费记录'], // 保存的表标题
          Sheets: {
            '自助缴费记录': Object.assign({},
              tmpdata, // 内容
              {
                '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
              })
          }
        }
        let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
          {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} // 这里的数据是用来定义导出的格式类型
        ))], {
          type: ''
        })  // 创建二进制对象写入转换好的字节流
        var href = URL.createObjectURL(tmpDown)  // 创建对象超链接

        // console.log('---',downName,href)
        this.outFile.download = downName + '.xlsx'  // 下载名称
        this.outFile.href = href  // 绑定a标签
        this.outFile.click()  // 模拟点击实现下载

        setTimeout(function () {  // 延时释放
          URL.revokeObjectURL(tmpDown) // 用URL.revokeObjectURL()来释放这个object URL
        }, 100)
      },
      s2ab: function (s) { // 字符串转字符流
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF
        }
        return buf
      },
      getCharCol: function (n) { // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
        let s = ''
        let m = 0
        while (n > 0) {
          m = n % 26 + 1
          s = String.fromCharCode(m + 64) + s
          n = (n - m) / 26
        }
        return s
      }
    }

  }


</script>



